package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;

@Service
public class EmployeeServiceImpl implements EmployeeService {



    @Autowired
    private EmployeeMapper employeeMapper;

    @PostConstruct
    public void init(){
        System.out.println("1111");
    }

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        //前端传递过来的明文密码
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        //将明文密码加密
        //将明文密码通过md5加密成密文
        /*
        * 。。。。。。。。。。。。
        * 000000000000000000
        *
        *
        *
        *
        * helloWord
        * */
        String passWordPlus = DigestUtils.md5DigestAsHex(password.getBytes());

        //将加密后的密码与数据库中的密码对比
        if (!passWordPlus.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 新增员工操作
     *
     * @param dto
     * @return
     */
    @Override
    public Result addEmp(EmployeeDTO dto) {
        //1.参数校验  非空判断   提升代码的健壮性 暴力测试
        if(dto.getUsername() == null ){
            return Result.error(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //2.根据账号去数据库中查询数据是否存在，如果存在就直接返回错误信息
        Employee employee = employeeMapper.getByUsername(dto.getUsername());
        if(employee != null){
            return Result.error(MessageConstant.ACCOUNT_EXEIT_FOUND);
        }

        //3.新增操作了， 调用mapper接口
        employee = new Employee();
            /**
            * beanUtils工具类，进行bean对象属性的属性拷贝使用
            * 要求：两个对象中的属性名称和属性类型必须完全一致的情况下才可以拷贝成功，否则失败
            *
            */
        BeanUtils.copyProperties(dto, employee);
        //密码
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        //状态
        employee.setStatus(StatusConstant.ENABLE);

        //创建时间和修改时间
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());

        // 创建人和修改人 TODO
        employee.setCreateUser(1L);
        employee.setUpdateUser(2L);

        employeeMapper.addEmp(employee);

        //4.响应数据
        return Result.success();
    }


    /**
     * 分页查询员工
     *
     * @param dto
     * @return
     */
    @Override
    public Result page(EmployeePageQueryDTO dto) {
        //1.非空判断
        if(dto.getPage()==null){
            dto.setPage(1);
        }
        if(dto.getPageSize()==null){
            dto.setPageSize(3);
        }

        //2.开启分页
        PageHelper.startPage(dto.getPage(), dto.getPageSize());


        //3.根据条件查询员工列表 调用mapper层
        Page<Employee> pageParam = employeeMapper.pageQuery(dto);

        //4，封装数据 返回数据
        PageResult pageResult = new PageResult();
        pageResult.setTotal(pageParam.getTotal());
        pageResult.setRecords(pageParam.getResult());

        return Result.success(pageResult);
    }


    /**
     * 启用禁用员工
     *
     * @param status 状态 0表示禁用1 表示启用
     * @param id  员工id
     * @return
     */
    @Override
    public Result updateStatus(Integer status, Long id) {
        //1.非空判断
        if(id == null){
            return Result.error(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        if(status == null){
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }

        //2.调用mapper接口 修改状态值

        Employee employee = new Employee();
        employee.setId(id);
        employee.setStatus(status);
        employee.setUpdateTime(LocalDateTime.now());
        employee.setCreateUser(BaseContext.getCurrentId());

        //调用mapper层
        employeeMapper.updateStatus(employee);
        //3.返回响应数据
        return Result.success();
    }


    /**
     * 根据id单一查询员工
     * @param id
     */
    @Override
    public Result getEmpById(Long id) {
        //1.非空判断
        if (id == null) {
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }

        //2.调用mapper
        Employee employeeMapperById = employeeMapper.getById(id);

        //3.返回数据
        return Result.success(employeeMapperById);
    }



    /**
     * 修改单一员工信息
     * @param dto
     * @return
     */
    @Override
    public Result updateEmp(EmployeeDTO dto) {
        //1.非空判断
        if(dto.getId() == null){
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }

        //2.调用mapper执行操作
        Employee employee = new Employee();
        BeanUtils.copyProperties(dto, employee);

        //3.返回数据
            //调用mapper层
        employeeMapper.updateStatus(employee);

        return Result.success();
    }


}
